﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ETWJ.Common
{
    public static class Common
    {
        #region AutoMapper封装

        /// <summary>
        /// DTO转换
        /// </summary>
        /// <typeparam name="TSource">原始类型</typeparam>
        /// <typeparam name="TDTO">转换成的类型</typeparam>
        /// <param name="p"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        public static TDTO ToDTO<TSource, TDTO>(TSource p, TDTO d)
            where TDTO : new()
        {
            if (p == null)
            {
                return new TDTO();
            }

            return AutoMapper.Mapper.Map<TDTO>(p);
        }


        public static List<TDTO> ToDTO<TSource, TDTO>(List<TSource> p, List<TDTO> d)
            where TDTO : new()
        {
            if (p == null)
            {
                List<TDTO> list = new List<TDTO>();
                list.Add(new TDTO());
                return list;
            }

            return AutoMapper.Mapper.Map<List<TDTO>>(p);
        }
        #endregion

        #region MD5加密
        public static string CalcMD5(string str)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
            return CalcMD5(bytes);
        }

        public static string CalcMD5(byte[] bytes)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] computeBytes = md5.ComputeHash(bytes);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }

        public static string CalcMD5(Stream stream)
        {
            using (MD5 md5 = MD5.Create())
            {
                stream.Position = 0;
                byte[] computeBytes = md5.ComputeHash(stream);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }
        #endregion
    }
}
